﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using HtmlAgilityPack;

namespace SimpleSocxs
{
    public partial class userpage : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            var username = Request["user"];
            var path = Request["path"];
            this.MasterPageFile = "~/users/" + username + "/" + VirtualPathUtility.GetFileName(path) + ".master";
        }

        protected override void Render(HtmlTextWriter writer)
        {
            var original_path = HttpContext.Current.Items["original_path"] as Uri;
            if (original_path == null || string.IsNullOrEmpty(HttpUtility.ParseQueryString(original_path.Query)["iframe"]))
            {
                base.Render(writer);
                return;
            }

            //if from iframe, clear contents in socxs_panel

            string html = InterceptHtml();

            html = RemoveSocxsPanelInnerHtml(html);
            html = html.Replace("</body>", "<script>if (parent && parent.initFrame) parent.initFrame()</script></body>");
            writer.Write(html);
        }

        private static string RemoveSocxsPanelInnerHtml(string html)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);

            var nodes = doc.DocumentNode.SelectNodes("//div[contains(@class,'socxs_panel') and not(contains(@class,'socxs_panels'))]");

            if (nodes != null)
                foreach (HtmlNode node in nodes)
                {
                    node.InnerHtml = string.Empty;
                }

            var sbuf = new StringWriter();
            doc.Save(sbuf);
            return sbuf.ToString();
        }

        string InterceptHtml()
        {
            var sbuf = new StringWriter();
            var tmpWriter = new HtmlTextWriter(sbuf);
            base.Render(tmpWriter);
            return sbuf.ToString();
        }
    }
}